package com.cpone.cloudweb.utils.bak;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DownFile {
	protected HttpServletRequest m_request;
	protected HttpServletResponse m_response;
	protected ServletContext m_application;
	private String m_contentDisposition;


	public void setContentDisposition(String s) {
		m_contentDisposition = s;
	}	
	
	/**
	 * ����
	 * @param servletContext
	 * @param httpSession
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @throws ServletException
	 */
	public final void initialize(ServletContext servletContext,
			HttpSession httpSession, HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse)
			throws ServletException {
		m_application = servletContext;
		m_request = httpServletRequest;
		m_response = httpServletResponse;
	}	
	
	
	/**
	 * 
	 * @param sourceFile   Դ�ļ�,�豣�渴�Ƶ��ļ�
	 * @param contentType  ��ʽ
	 * @param toFile       Ŀ�ı����ļ�
	 * @param i			   ÿ�δ����ļ����ֽ���
	 * @throws ServletException
	 * @throws IOException
	 */
	public void downloadFile(String sourceFile, String contentType, String toFile, int i)
			throws ServletException, IOException {
		
		if (sourceFile == null)
			throw new IllegalArgumentException((new StringBuilder("File '"))
					.append(sourceFile).append("' not found.").toString());
		
		if (sourceFile.equals(""))
			throw new IllegalArgumentException((new StringBuilder("File '"))
					.append(sourceFile).append("' not found.").toString());
		
		if (!isVirtual(sourceFile)){
			System.out.println("�ļ�·������...");
			throw new SecurityException("Physical path is denied(�ļ�·������).");
		}
		
		File file = new File(sourceFile);
		FileInputStream fileinputstream = new FileInputStream(file);
		try {
			long fileLen = file.length();
			int k = 0;
			byte byteLen[] = new byte[i];
			
			//���ø�ʽ
			if (contentType == null)
				m_response.setContentType("application/x-msdownload");
			else if (contentType.length() == 0)
				m_response.setContentType("application/x-msdownload");
			else
				m_response.setContentType(contentType);
			
			//�����ļ�����
			m_response.setContentLength((int) fileLen);
			
			m_contentDisposition = m_contentDisposition 
					== null ? "attachment;"	: m_contentDisposition;
			
			if (toFile == null)
				m_response.setHeader("Content-Disposition", (new StringBuilder(
						String.valueOf(m_contentDisposition))).append(" filename=")
						.append(toUtf8String(getFileName(sourceFile))).toString());
			else if (toFile.length() == 0)
				m_response.setHeader("Content-Disposition", m_contentDisposition);
			else
				m_response.setHeader("Content-Disposition", (new StringBuilder(
						String.valueOf(m_contentDisposition))).append(" filename=")
						.append(toUtf8String(getFileName(toFile))).toString());
			
			while ((long) k < fileLen) {
				int j = fileinputstream.read(byteLen, 0, i);
				k += j;
				m_response.getOutputStream().write(byteLen, 0, j);
			}
		} catch (Exception e) {//�쳣�ر���
			fileinputstream.close();
		}
		
		fileinputstream.close();
	}


	
	
	/**
	 * �ж��ļ��Ƿ����
	 * @param filePath �ļ�·��
	 * @return
	 */
	private boolean isVirtual(String filePath) {
		
		//�������д����ڱ�����û��ʵ����;,ֻ�����������ʾ��������·��
		//String path = m_application.getRealPath(filePath);
		//System.out.println("��������·��:" + path);
		
		if (filePath != null) {
			File file = new File(filePath);
			//��File��exists()���������ж��Ƿ����
			System.out.println(filePath + " ����.");
			return file.exists();
		} else {
			System.out.println(filePath + " ������.");
			return false;
		}
	}
	
	
	/**
	 * �ַ�ת��
	 * @param s
	 * @return
	 */
	public static String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= '\377') {
				sb.append(c);
			} else {
				byte b[];
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append((new StringBuilder("%")).append(
							Integer.toHexString(k).toUpperCase()).toString());
				}

			}
		}
		return sb.toString();
	}

	
	/**
	 * �õ��ļ�����
	 * @param filePath �ļ�·��
	 * @return
	 */
	private String getFileName(String filePath) {
		int i = 0;
		
		i = filePath.lastIndexOf('/');
		if (i != -1)
			return filePath.substring(i + 1, filePath.length());
		
		i = filePath.lastIndexOf('\\');
		if (i != -1)
			return filePath.substring(i + 1, filePath.length());
		else
			return filePath;
	}

}
